import React  from 'react';
import {Button, Checkbox, Col, Input, message, Modal, Row, Select, Switch} from 'antd';
import { Form, Icon } from '@ant-design/compatible';
import { connect } from 'dva';
import tools from '../../utils';
import md5 from '../../utils/md5';
import { pageSize, modalWidth } from '../../../config';
import { PageHeaderLayout, StandardTable, SearchForm, IconButton, PageCard } from '../../components';
import Authorized from '../../utils/Authorized';

const basicName = '用户';
const reqApi = 'user';
let changeValues = {};
const formItemLayout = {
	labelCol: { md: 3 },
	wrapperCol: { md: 21 },
};
const formItemLayout2 = {
	labelCol: { md: 6, xs: 7 },
	wrapperCol: { md: 18, xs: 17 },
};
const { Option } = Select;

class page extends React.Component {
	state = {
		loading: true,
		visible: false,
		dialogLoading: false,
		dialogTitle: '',
		dialogAction: '',
		selectedRows: [],
		searchs: [],
		pagination: {
			current: 1,
			pageSize,
			onShowSizeChange: (_, size) => {
				const { pagination } = this.state;
				pagination.pageSize = size;
			},
		},
		editId: 0,
		beforeName: '', // 编辑时记录初始值
	};

	componentDidMount() {
		this.funcGetListData();

		const payload = { currentPage: 1, pageSize: 100 };
		const { dispatch } = this.props;
		dispatch({
			type: reqApi + '/role',
			payload,
		}).then(() => {
			dispatch({
				type: reqApi + '/dept',
				payload,
			});
		});
	}

	// 表格列
	columns = () => {
		const { props } = this;

		return [
      {
        title: "用户ID",
        dataIndex: "id",
        width: 62,
      },
			{
				title: "用户名",
				title2: "用 户 名",
				dataIndex: "userName",
				type: "text",
				render: (text, record) => (
					<Authorized authority={() => tools.funcCheckValid(props, 'edit')} noMatch={text}>
						<a
							title="编辑"
							onClick={() => {
								this.funcOpenForm(record);
								this.setState({ editId: record.id });
							}}
						>
							{text}
						</a>
					</Authorized>
				),
			},
			{
				title: "姓名",
				dataIndex: "name",
			},
			{
				title: "手机号码",
				dataIndex: "phone",
				width: 120,
			},
			{
				title: '用户状态',
				dataIndex: 'status',
				width: 80,
				type: 'select',
				sub: [['1', '正常'], ['0', '关闭']],
				render: text => text === '1' ?
					<Icon type='check' style={{ color: 'limegreen' }} /> :
					null,
			},
			{
				title: "注册日期",
				dataIndex: "addTime",
				width: 110,
				render: text => <div style={{ color: "darkgray" }}>{text.substr(0, 10)}</div>,
			},
		];
	};

	// 读取表记录
	funcGetListData = () => {
		this.setState({
			loading: true,
			selectedRows: [], // 换页时清除表格行选中状态
		});

		const { state } = this;
		const { searchs, pagination } = state;
		const { current, pageSize } = pagination;
		const { dispatch } = this.props;

		dispatch({
			type: reqApi + '/list',
			payload: {
				currentPage: current,
				pageSize,
				searchs,
			},
		}).then(() => this.setState({ loading: false }));
	};

	// 记录查询表单提交
	funcOnSubmitSearch = (searchs) => {
		const { state } = this;
		state.pagination.current = 1;
		this.setState({ searchs }, this.funcGetListData);
	};

	// 弹出表单
	funcOpenForm = (record) => {
		const action = record ? "edit" : "create";

		this.setState({
			visible: true,
			dialogTitle: tools.funcDlgTitle(basicName, action),
			dialogAction: action,
		}, () => {
			const { form } = this.props;
			form.resetFields();
			if (action === "edit") {
				const { status, userName } = record;
				form.setFieldsValue({
					...record,
					status: status === '1',
				});
				changeValues = {};
				this.setState({ beforeName: userName });
			}
		});
	};

	// 保存
	funcSave = () => {
		const { state } = this;
		const { form, dispatch } = this.props;

		form.validateFields((error) => {
			if (error) return error;

			const model = { ...changeValues };
			const act = state.dialogAction;
			if (act === "edit") {
				if (tools.funcGetObjNum(changeValues) === 0) {
					message.info('你未做任何更改').then();
					return;
				}

				model.id = state.editId;
				if (model.passwd)
					model.passwd = md5.md5(model.passwd);
			} else {
				model.passwd = md5.md5(model.passwd);
				if (model.status === undefined)
					model.status = true; // 默认的用户状态是启用
			}
			if (model.depts)
				model.depts = model.depts.toString();

			this.setState({ dialogLoading: true });

			dispatch({
				type: reqApi + '/' + act,
				payload: { model },
			}).then(() => {
				this.setState({ dialogLoading: false });

				const { props } = this;
				const { success } = props[reqApi];
				if (success) {
					this.setState({ visible: false });
					this.funcGetListData();
				}
			});
		});
	};

	// 删除
	funcDelete = () => {
		const { state } = this;
		let names = [], ids = [];
		for (let i = 0; i < state.selectedRows.length; i += 1) {
			const item = state.selectedRows[i];
			const { id, name } = item;
			names.push(name);
			ids.push(id);
		}

		Modal.confirm({
			title: "删除?",
			content: (
				<div>
					<div>你即将删除以下记录：</div>
					<div>{names + ''}</div>
					<div>请确认是否删除？</div>
				</div>
			),
			okText: "是",
			okType: "danger",
			cancelText: "否",
			onOk: () => {
				this.setState({ loading: true });

				const { dispatch } = this.props;
				dispatch({
					type: reqApi + '/dele',
					payload: { ids: ids + '' },
				}).then(() => {
					const { props } = this;
					const { success } = props[reqApi];
					if (success) this.funcGetListData();
					else this.setState({ loading: false });
				});
			},
		});
	};

	// 检查名称是否被占用
	funcCheckName = (_, value) => {
		if (!value) {
			return Promise.reject('请输入' + basicName + '名称');
		}

		const { state } = this;
		if (state.dialogAction === 'edit' && value === state.beforeName) {
			return Promise.resolve();
		}

		const { props } = this;
		if (props[reqApi].names.indexOf(value) >= 0) {
			return Promise.reject('这个' + basicName + '名称已经存在，请换个名称。');
		}

		return Promise.resolve();
	};

	render() {
		const { state, props } = this;
		const { getFieldDecorator } = props.form;

		return (
			<PageHeaderLayout title={props.route.name}>
				<PageCard
					children={(
						<div>
							<SearchForm fields={this.columns()} onSubmit={this.funcOnSubmitSearch} />
							<Button.Group>
								<Authorized authority={() => tools.funcCheckValid(props, 'create')}>
									<IconButton
										text={'新增' + basicName}
										onClick={() => this.funcOpenForm()}
										style={{ marginBottom: 16 }}
									/>
								</Authorized>
								<Authorized authority={() => tools.funcCheckValid(props, 'delete')}>
									<IconButton
										text={'删除' + basicName}
										type='danger'
										onClick={this.funcDelete}
										disabled={!state.selectedRows.length}
										style={{ marginBottom: 16 }}
									/>
								</Authorized>
							</Button.Group>
							<StandardTable
                addNum={false}
								columns={this.columns()}
								loading={state.loading}
								data={{
									list: props[reqApi].data,
									pagination: { ...state.pagination, total: props[reqApi].total },
								}}
								selectedRows={state.selectedRows}
								onSelectRow={(selectedRows) => this.setState({ selectedRows })}
								onChange={(pageParams) => {
									const { pagination } = this.state;
									pagination.current = pageParams.current;
									this.funcGetListData();
								}}
								scrollX={640}
							/>
						</div>
					)}
				/>

				<Modal
					width={modalWidth}
					title={state.dialogTitle}
					visible={state.visible}
					onOk={this.funcSave}
					onCancel={() => this.setState({ visible: false })}
					bodyStyle={{ paddingBottom: 0 }}
					footer={[
						<IconButton
							key='cancel'
							text='取消'
							type='default'
							onClick={() => this.setState({ visible: false })}
						/>,
						<IconButton
							key='save'
							text='保存'
							loading={state.dialogLoading}
							onClick={this.funcSave}
						/>,
					]}
				>
					<Form>
						<Row gutter={{ md: 24, sm: 8 }}>
							<Col md={12} sm={24}>
								<Form.Item label="用户名" {...formItemLayout2}>
									{getFieldDecorator("userName", {
										rules: [{ required: true, validator: this.funcCheckName }],
									})(<Input maxLength={20} autoFocus autoComplete="nope" />)}
								</Form.Item>
							</Col>
							<Col md={12} sm={24}>
								<Form.Item label="登录密码" {...formItemLayout2}>
									{getFieldDecorator("passwd", {
										rules: [{ required: true, message: "请输入登录密码" }],
									})(<Input maxLength={20} type="password" autoComplete="new-password" />)}
								</Form.Item>
							</Col>

							<Col md={12} sm={24}>
								<Form.Item label="姓名" {...formItemLayout2}>
									{getFieldDecorator("name", {
										rules: [{ required: true, message: "请输入您的姓名" }],
									})(<Input maxLength={10} />)}
								</Form.Item>
							</Col>
							<Col md={12} sm={24}>
								<Form.Item label="手机号码" {...formItemLayout2}>
									{getFieldDecorator("phone")
									(<Input type="number" min={13000000000} max={19999999999} />)}
								</Form.Item>
							</Col>

							<Col md={12} sm={24}>
								<Form.Item label="用户角色" {...formItemLayout2}>
									{getFieldDecorator("roles", {
										rules: [{ required: true, message: "请选择用户角色" }],
									})(
										<Select>
											{props[reqApi].roleData.map((item) => {
												const { id, name } = item;
												return <Option key={id} value={id}>{name}</Option>;
											})}
										</Select>
									)}
								</Form.Item>
							</Col>
							<Col md={12} sm={24}>
								<Form.Item label="用户状态" {...formItemLayout2}>
									{getFieldDecorator("status", {
										initialValue: true,
										valuePropName: "checked",
									})(
										<Switch
											checkedChildren={<Icon type="check" />}
											unCheckedChildren={<Icon type="close" />}
										/>
									)}
								</Form.Item>
							</Col>

							<Col span={24}>
								<Form.Item label='可见系部' {...formItemLayout}>
									{getFieldDecorator('depts')(
										<Checkbox.Group
											options={props[reqApi].deptData.map(({id, name}) => {
												return {
													label: name,
													value: id,
												};
											})}
										/>
									)}
								</Form.Item>
							</Col>

							<Col span={24}>
								<Form.Item label="备注" {...formItemLayout}>
									{getFieldDecorator("remark")(
										<Input.TextArea maxLength={255} autoSize={{ minRows: 3, maxRows: 5 }} />
									)}
								</Form.Item>
							</Col>
						</Row>
					</Form>
				</Modal>
			</PageHeaderLayout>
		);
	}
}

const page2 = Form.create({
	onValuesChange: (props, value) => {
		changeValues = { ...changeValues, ...value };
	},
})(page);
export default connect(({ user, menu }) => ({ user, menu }))(page2);
